﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System;
using System.Threading.Tasks;
using BitwiseOre.SharedMemory.Core.Common;

namespace BitwiseOre.SharedMemory.Core
{
    internal sealed class Reader : IReader
    {
        private readonly IConnectionQueues _connectionBuffers;
        private readonly Func<TimeSpan, ITimeoutHelper> _createTimeoutHelper;

        public Reader(IConnectionQueues connectionBuffers, Func<TimeSpan, ITimeoutHelper> createTimeoutHelper)
        {
            _connectionBuffers = connectionBuffers;
            _createTimeoutHelper = createTimeoutHelper;
        }

        public Task<int> ReadAsync(ArraySegment<byte> array, TimeSpan timeout)
        {
            var helper = _createTimeoutHelper(timeout);

            var count = _connectionBuffers.ReadFromCurrentBuffer(array);
            return count != 0
                       ? count.ToCompletedTask()
                       : _connectionBuffers.ReadFromNextBuffer(array, helper);
        }

        public int ReadByte(TimeSpan timeout)
        {
            var helper = _createTimeoutHelper(timeout);

            var result = _connectionBuffers.ReadByteFromCurrentBuffer();
            if (result != -1)
            {
                return result;
            }

            var buffer = new byte[1];
            var task = _connectionBuffers.ReadFromNextBuffer(new ArraySegment<byte>(buffer), helper);
            task.Wait();

            return task.Result == 0 ? -1 : buffer[0];
        }

        public int Read(ArraySegment<byte> array, TimeSpan timeout)
        {
            var helper = _createTimeoutHelper(timeout);

            var count = _connectionBuffers.ReadFromCurrentBuffer(array);
            return count != 0
                       ? count
                       : _connectionBuffers.ReadFromNextBuffer(array, helper).Result;
        }

        public void Flush()
        {
            _connectionBuffers.FlushReadBuffer();
        }
    }
}